package com.briup.cms.service.impl;

import com.briup.cms.bean.Role;
import com.briup.cms.dao.RoleDao;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.RoleService;
import com.briup.cms.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public Page<Role> findAll(Integer pageNum, Integer pageSize) throws ServiceException {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return roleDao.findAll(pageRequest);
    }

    //角色名称非空且唯一
    @Override
    public void saveOrUpdateRole(Role role) throws ServiceException {
        //非空
        if (role.getName()==null||role.getName().trim().equals("")){
            throw  new ServiceException(ResultCode.USER_NAME_ISNULL);
        }
        //唯一
        Role role1 = findRoleByName(role.getName());
        if (role1!=null){
            throw new ServiceException(ResultCode.USER_HAS_EXISTED);
        }
        //表中没有要插入的Role
        roleDao.save(role);
    }

    @Override
    public void deleteRoleInBatch(List<Long> ids) throws ServiceException {
        for (Long id:ids){
            roleDao.deleteById(id);
        }
    }

    @Override
    public void deleteRoleById(Long id) throws ServiceException {
        Role role = findRoleById(id);
        if (role==null){
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        roleDao.deleteById(id);
    }

    @Override
    public Role findRoleByName(String name) throws ServiceException {
        //非空
        if (name==null||name.trim().equals("")){
            throw  new ServiceException(ResultCode.USER_NAME_ISNULL);
        }

        return roleDao.findByName(name);
    }

    @Override
    public Role findRoleById(Long id) throws ServiceException {
        return roleDao.findById(id).orElse(null);
    }
}
